<template>
  <el-card>
    <div slot="header">
      <h3>{{ getPageTitle() }}</h3>
    </div>
    <div>
      <!-- 按钮操作栏 -->
      <BtnRender :render="renderBtnsBar" />
      <!-- 发起原因输入框 -->
      <LaunchReasonInput :reason.sync="launchReason" />
      <!-- 表格 -->
      <el-row>
        <SkusTable
          showActionCol
          :loading="tableInfo.loading"
          :data-source="tableInfo.list"
          :columns="tableInfo.columns"
          :actionRender="renderTableBtnAction"
        />
      </el-row>
      <!-- 表尾字段 -->
      <FooterFields :footerFields="footerFields" />
    </div>
    <!-- 关联商品-SPU维度弹框 -->
    <SpuAssociatedDialog
      ref="link"
      :columns="goodsLinked.columns"
      :requestApi="goodsLinked.requestApi"
      :requestParams="goodsLinked.requestParams"
      :distinctParams="goodsLinked.distinctParams"
      @getRowList="getTableDataByGoodsLinked"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getTableDataBySeniorLinked"
    />
  </el-card>
</template>
<script>
import { mapGetters, mapMutations, mapState } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import BtnRender from '@/components/JSXRender/BtnRender';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import SpuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { requestToData, requestToStatus, requestToExport } from '@/api/commonHttp';
import { getTableColumns } from './constants';
import { createExcelByExport, isResponseSuccessState } from '@/utils/bizUtils';
import { getArraysByMaps, getCanOpeState } from '@/utils/getUtils';
import { requiredParams } from '@/components/common/dialog/associatedGoods/constants/spuDimension';
import getCompRender from '@/mixins/getCompRender';
import { getFooterFieldsService, getSpuRelSeriesInfoService } from '@/api/commodity/common';
import { getProductListService, getProductNameFinalService } from '@/api/commodity/commodityInfoEdit/schemaInfoEdit';
export default {
  mixins: [getCompRender],
  components: {
    BtnRender,
    LaunchReasonInput,
    SkusTable,
    FooterFields,
    SeniorLinkedDialog,
    SpuAssociatedDialog
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SPU编码', prop: 'spuNo', type: 'textarea' }],
        dataSource: [{ spuNo: '' }],
        isSenior: false
      },
      goodsLinked: {
        requestApi: {
          url: ['/sysback/update/product/structure/getProductList'],
          type: 'post'
        },
        requestParams: requiredParams.requestParams,
        distinctParams: requiredParams.distinctParams,
        columns: [
          { type: 'selection', width: 60 },
          { title: '商品名称', key: 'productNameFinal' },
          { title: 'SPU编码', key: 'spuNo' },
          { title: '品牌', key: 'brandName' },
          { title: '操作', slot: 'action', fixed: 'right' }
        ],
      },
      btnLoading: {
        export: false, // 导出
        ok: false, // 暂存和提交
      },
      launchReason: '', // 发起原因
      tableInfo: {
        list: [],
        columns: [],
        loading: false
      },
      skuSpec: {
        list: [], // row => SPU下SKU规格列表
        loading: false
      },
      recordNo: '', // 单据号
      footerFields: {}, // 表尾字段
    }
  },
  mounted () {
    this.setCanOpeState()
    this.loadInitDataInMounted();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    ...mapState('commonComps/spuAssociatedModal', ['associatedRowList'])
  },
  watch: {
    '$route.path' (newValue) { // 解决表单编辑页直接跳转菜单页面有缓存的问题
      this.$router.go(0);
    }
  },
  methods: {
    ...mapMutations('commonComps/spuAssociatedModal', [
      'CHANGE_MODAL_SWITCH', 'CANCEL_GOODS', 'ASSOCIATED_GOODS'
    ]),
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // jsx-render渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [
        { label: '高级关联', method: this.handleSeniorLinked, icon: 'el-icon-link', size: 'large', hasAuth: true },
        { label: '关联商品', method: this.handleGoodsLinked, size: 'large', hasAuth: true },
        {
          label: '模板导入',
          action: 'sysback/update/product/structure/saveStructureToPage',
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: state => { this.tableInfo.loading = state }
        },
        { label: '模板导出', method: this.handleExport, loading: this.btnLoading.export, size: 'large', disabled: this.isEmptyForCurrentList() },
        { label: '暂存', method: this.handleStag, loading: this.btnLoading.ok, size: 'large', disabled: this.isEmptyForCurrentList(), canOpeState: this.canOpeState },
        { label: '提交', method: this.handleSubmit, loading: this.btnLoading.ok, size: 'large', disabled: this.isEmptyForCurrentList(), canOpeState: this.canOpeState },
      ]
      if (this.isFromEditPage()) { // 表单修改页面展示返回按钮，菜单页面无需展示
        btnsBar.push({ label: '返回', method: this.handleGoBack, size: 'large' });
      }
      const finalBtns = btnsBar.filter(item => item.canOpeState != false)
      return getBtnsBar(h, finalBtns, this.showBtn);
    },
    // jsx-render渲染表格操作栏
    renderTableBtnAction (h, { row }) {
      const viewSpecBtn = <el-popover
        placement="right"
        trigger="click"
      >
        <el-table data={this.skuSpec.list} height={300} v-loading={this.skuSpec.loading}>
          <el-table-column minWidth="150" property="specDetailStr" label="规格" />
          <el-table-column minWidth="150" property="skuNo" label="SKU编码" />
        </el-table>
        <el-button slot="reference" type="text" onClick={() => { this.handleViewSpec(row) }}>查看规格</el-button>
        <span slot="reference">{row.skuList ? row.skuList[0]?.specDetailStr : '' }</span>
      </el-popover>
      const deleteBtn = <el-button type="text" onClick={() => { this.handleDelete(row) }}>删除</el-button>
      return <div class="table-action">{ viewSpecBtn } { deleteBtn }</div>;
    },
    // 来自表单修改页面
    isFromEditPage () { return this.$route.query?.type === 'edit' },
    // 当前列表为空 （默认表格数据）
    isEmptyForCurrentList (list = this.tableInfo.list) {
      return list.length === 0;
    },
    // 必填项有空值
    hasEmptyValForRequiredFields () {
      const emptyItemNameList = this.getEmptyTitleListByRequiredFields();
      if (emptyItemNameList.size !== 0) {
        this.$message.warning(`${[...emptyItemNameList].join('，')}不能为空`);
        return true;
      }
    },
    // 助记码校验
    validateHelpCode (row) {
      if (!row.productNameUpdate) {
        row.helpCodeUpdate = '';
        this.$message.warning('商品名称不能为空');
        return true;
      }
      if (!row.productNameTypeUpdate) {
        row.helpCodeUpdate = '';
        this.$message.warning('是否包含品牌不能为空');
        return true;
      }
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      this.setTableColumns();
      const { recordNo } = this.$route.query;
      if (recordNo) {
        this.recordNo = recordNo;
        this.getTableDataByRecordNo();
        this.getFieldsInfo(recordNo);
      }
    },
    // 获取字段信息
    async getFieldsInfo (recordNo) {
      const retData = await getFooterFieldsService({ recordNo }, '.footer_fields_card');
      if (retData) {
        this.launchReason = retData.launchReason;
        this.footerFields = retData;
      }
    },
    // 设置表格columns
    setTableColumns () {
      this.tableInfo.columns = getTableColumns({
        getElInput: this.getElInput,
        getElSelect: this.getElSelect,
        handleInputBlurByProductName: this.handleInputBlurByProductName,
        handleInputBlurByKeyword: this.handleInputBlurByKeyword,
        renderSeriesSelect: this.renderSeriesSelect,
        handleChangeByProductType: this.handleChangeByProductType
      });
    },
    // 高级关联
    handleSeniorLinked () {
      sessionStorage.setItem('buttonId', getBtnsId('高级关联'));
      this.seniorLinked.visible = true;
    },
    // 关联商品
    handleGoodsLinked () {
      sessionStorage.setItem('buttonId', getBtnsId('关联商品'));
      this.CHANGE_MODAL_SWITCH(true);
    },
    // 上传成功回调
    handleUploadSuccess (res) {
      this.stopTableLoading();
      const { retStatus, retData, retMessage } = res;
      if (isResponseSuccessState(retStatus)) {
        this.$message.success('导入成功');
        this.tableInfo.list = retData;
      } else {
        this.$message.error(retMessage || '导入失败');
      }
    },
    // 导出
    handleExport () {
      this.exportSchemaInfo();
    },
    // 暂存
    handleStag () {
      this.stagSchemaInfo();
    },
    // 提交
    handleSubmit () {
      this.stagSchemaInfo(true);
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'chageFromManageList' });
    },
    // 查看规格
    handleViewSpec (row) {
      this.getSkuSpecListBySpu(row.uuid);
    },
    // 删除
    handleDelete (row) {
      this.tableInfo.list = this.tableInfo.list.filter(item => item.spuNo !== row.spuNo);
      if (!this.seniorLinked.isSenior) { this.CANCEL_GOODS({ row }); } // 关联商品特殊处理
    },
    // 更改商品名称
    handleInputBlurByProductName (row) {
      this.updatePresentValByProductNameFinal(row);
      if (this.validateHelpCode(row)) { return false; }
      this.updateProductNameFinal(row);
    },
    // 更改关键词
    handleInputBlurByKeyword (row) {
      this.getUpdateInfoByKeyword(row);
    },
    // 更新商品名称（含品牌）的现值
    updatePresentValByProductNameFinal (row) {
      if (row.productNameTypeUpdate === '1') { // 包含品牌
        row.productNameFinalUpdate = `${row.joinBrandName} ${row.productNameUpdate}`;
      }
      if (row.productNameTypeUpdate === '2') { // 不包含品牌
        row.productNameFinalUpdate = row.productNameUpdate;
      }
    },
    // 更新关联弹框关联数据
    updateLinkedInfoByGoodsLinked (list = this.tableInfo.list) {
      list.forEach((row) => { this.ASSOCIATED_GOODS({ row }); });
    },
    // 获取页面标题
    getPageTitle () {
      const title = '修改架构信息'
      if (this.isFromEditPage()) { return `${title}-表单修改页面`; }
      return title;
    },
    // 获取SPU下的SKU的规格列表
    async getSkuSpecListBySpu (productUuid) {
      const retData = await requestToData({
        url: `/sysback/update/product/structure/getProductSkuList?productUuid=${productUuid}`,
        type: 'get',
      }, () => { this.skuSpec.loading = true; }, () => { this.skuSpec.loading = false; });
      this.skuSpec.list = retData;
    },
    // 获取预处理现值的表列key集合
    getPreInitUpdateValKeys () {
      return this.tableInfo.columns
        .filter(item => item.children)
        .map(item => item.children[0].key)
        .filter(item => item);
    },
    // 获取初始化表格数据现值
    getInitUpdateValByTableData (list) {
      if (!list) { return []; }
      const preInitUpdateValKeys = this.getPreInitUpdateValKeys();
      return list.map(item => {
        const updateVals = {};
        preInitUpdateValKeys.forEach(key => {
          // 处理特殊表列
          // 商品类型
          if (key === 'productTypeStr') {
            updateVals.productTypeUpdate = item.productType || '01';
            return;
          }
          // 是否采集
          if (key === 'centralBuyStateStr') {
            updateVals.centralBuyStateUpdate = item.centralBuyState || '2';
            return;
          }
          // 加价类型
          if (key === 'addPriceTypeStr') {
            updateVals.addPriceTypeUpdate = item.addPriceType || '1';
            return;
          }
          // 关键词
          if (key === 'keywordName') {
            updateVals.keywordUuidUpdate = item.keywordUuid;
            updateVals.keywordNameUpdate = item.keywordName;
            return;
          }
          // 商品名称类型
          if (key === 'productNameType') {
            updateVals.productNameTypeUpdate = item.productNameTypeOnBrand;
            return;
          }
          // 商品名称
          if (key === 'productNameFinal') {
            updateVals.productNameFinalUpdate = item.productNameFinalOnBrand;
            return;
          }
          // 助记码
          if (key === 'helpCode') {
            updateVals.helpCodeUpdate = item.helpCodeOnBrand;
            return;
          }
          if (key === 'brandseries') {
            updateVals.brandseriesUuidUpdate = item.brandseriesUuid
          }
          updateVals[`${key}Update`] = item[key];
        });
        // return { ...item, ...updateVals }
        return {
          ...item,
          ...updateVals,
          // 选择商品类型 不让选择 项目商品 https://www.tapd.cn/41685229/prong/stories/view/1141685229001232400
          productTypeOptions: item.productTypeOptions.filter(item => item.optionValue != '10')
        }
      }).filter(item => item);
    },
    // 获取高级关联查询入参
    getSearchParamsBySeniorLinked (spus) {
      const searchParam = [
        { 'name': 'categoryPath', 'value': '' }, { 'name': 'categoryPath_q', 'value': 'Like' },
        { 'name': 'productNameFinal', 'value': '' }, { 'name': 'productNameFinal_q', 'value': 'Like' },
        { 'name': 'spuNo', 'value': '' }, { 'name': 'spuNo_q', 'value': 'EQ' },
        { 'name': 'notInUuidStr', 'value': '' }, { 'name': 'notInUuidStr_q', 'value': 'NotIN' },
        { 'name': 'spus', 'value': spus.join(',') }
      ]
      return { searchParam: JSON.stringify(searchParam) }
    },
    // 获取表格数据 by 高级关联
    async getTableDataBySeniorLinked (spuNos) {
      const data = this.getSearchParamsBySeniorLinked(spuNos);
      const loadingFn = state => { this.tableInfo.loading = state };
      const res = await getProductListService(data, loadingFn);
      this.seniorLinked.isSenior = true;
      this.tableInfo.list = this.getInitUpdateValByTableData(res?.retData?.results ?? []);
    },
    // 获取表格数据 by 关联商品
    async getTableDataByGoodsLinked () {
      const spuNos = [];
      spuNos.push(...getArraysByMaps(this.associatedRowList).map(row => row.spuNo));
      if (spuNos.length == 0) return (this.tableInfo.list = [])
      const data = this.getSearchParamsBySeniorLinked(spuNos);
      const loadingFn = state => { this.tableInfo.loading = state };
      const res = await getProductListService(data, loadingFn);
      this.seniorLinked.isSenior = false;
      this.tableInfo.list = this.getInitUpdateValByTableData(res?.retData?.results ?? []);
    },
    // 获取表格数据 by 单据号
    async getTableDataByRecordNo () {
      const retData = await requestToData({
        url: `/sysback/product/update/record/queryRecordStructure?recordNo=${this.recordNo}`,
        type: 'post'
      }, this.enableTableLoading, this.stopTableLoading);
      this.tableInfo.list = retData;
      this.updateLinkedInfoByGoodsLinked();
    },
    // 获取更新信息 by 关键词
    async getUpdateInfoByKeyword (row) {
      const retData = await requestToData({
        url: `/sysback/product/keyword/getByExactKeyword?exactKeyword=${row.keywordNameUpdate}`,
        type: 'get'
      }, this.enableTableLoading, this.stopTableLoading);
      if (retData) {
        row.keywordNameUpdate = retData.keyword;
        row.keywordUuidUpdate = retData.keywordUuid;
      } else {
        row.keywordUuidUpdate = '';
      }
    },
    // 获取必填项为空的表列标题集合
    getEmptyTitleListByRequiredFields () {
      const isEmptyItemNameList = new Set();
      // 筛选必填表列
      const requiredFieldColumns = this.tableInfo.columns.filter(item => item.required);
      this.tableInfo.list.forEach(item => {
        requiredFieldColumns.forEach(column => {
          const val = item[column.children[1].key];
          if (!val && val !== 0) {
            isEmptyItemNameList.add(`${column.title}现值`);
          }
        });
      });
      return isEmptyItemNameList;
    },
    // 获取暂存或导出入参
    getParamsByStagOrExport (type) {
      return this.tableInfo.list.map(item => {
        // 可编辑的现值集合
        return {
          productKey: type === 'export' ? item.uuid : item.spuNo, // 如果是导出，取uuid，暂存取spuNo
          joinBrandName: item.joinBrandName,
          productNameUpdate: item.productNameUpdate, // 商品名称
          productNameTypeUpdate: item.productNameTypeUpdate, // 是否包含品牌
          productNameFinalUpdate: item.productNameFinalUpdate, // 商品名称（含品牌）
          keywordNameUpdate: item.keywordNameUpdate, // 关键词
          keywordUuidUpdate: item.keywordUuidUpdate, // 关键词uuid
          helpCodeUpdate: item.helpCodeUpdate, // 助记码
          productTypeUpdate: item.productTypeUpdate, // 商品类型
          disCentreUpdate: item.disCentreUpdate, // 集散地
          centralBuyStateUpdate: item.centralBuyStateUpdate, // 是否采集
          subtitleUpdate: item.subtitleUpdate, // 副标题
          addPriceTypeUpdate: item.addPriceTypeUpdate, // 加价类型
          brandseriesUpdate: item.brandseriesUpdate, // 系列名称
          brandseriesUuidUpdate: item.brandseriesUuidUpdate, // 系列id
        }
      }).filter(item => item);
    },
    // 暂存架构信息
    async stagSchemaInfo (isSubmit) {
      if (this.hasEmptyValForRequiredFields()) { return false; }
      const retData = await requestToData({
        url: '/sysback/update/product/structure/saveStructure',
        type: 'post',
        data: {
          recordNo: this.recordNo,
          launchReason: this.launchReason, // 发起原因
          inputList: this.getParamsByStagOrExport()
        }
      }, () => { this.btnLoading.ok = true; }, () => { this.btnLoading.ok = false; });
      if (!retData) { return false; }
      // 当前操作是暂存，再进行提示
      if (!isSubmit) { this.$message.success('暂存成功'); }
      this.recordNo = retData.recordNo;
      // 当前操作是提交，请求提交方法
      if (isSubmit) { this.submitSchemaInfo(); }
    },
    // 提交架构信息
    async submitSchemaInfo () {
      const retStatus = await requestToStatus({
        url: `/sysback/update/product/structure/commitStructure?recordNo=${this.recordNo}`,
        type: 'post'
      }, () => { this.btnLoading.ok = true; }, () => { this.btnLoading.ok = false; });
      if (retStatus) {
        this.$message.success('提交成功');
        this.$router.push({ name: 'chageFromManageList' });
      }
    },
    // 导出架构信息
    async exportSchemaInfo () {
      const res = await requestToExport({
        url: '/sysback/update/product/structure/exportPageToExcelPost',
        type: 'post',
        data: this.getParamsByStagOrExport('export')
      }, () => { this.btnLoading.export = true; }, () => { this.btnLoading.export = false; });
      createExcelByExport({ res, excelTitle: '修改架构信息' });
    },
    // 启用表格loading
    enableTableLoading () {
      this.tableInfo.loading = true;
    },
    // 停用表格loading
    stopTableLoading () {
      this.tableInfo.loading = false;
    },
    // 渲染系列下拉
    renderSeriesSelect (h, { row }) {
      const setBrandseriesUuidUpdate = (row, val) => {
        const target = (row?.brandseriesOptions ?? []).find(item => item.series == val)
        row.brandseriesUuidUpdate = target?.seriesUuid
      }
      return <el-select
        v-model={row.brandseriesUpdate}
        onChange={val => { setBrandseriesUuidUpdate(row, val) }}
        on-visible-change={val => { val && this.setRowSeriesOptions(row) }}
      >
        {(row?.brandseriesOptions ?? []).map(
          item => <el-option key={item.seriesUuid} value={item.series} label={item.series} />
        )}
      </el-select>
    },
    // 设置系列下拉选项集合
    async setRowSeriesOptions (row) {
      const data = {
        categoryUuid: row.categoryUuid,
        brandUuid: row.brandUuid,
        productType: row.productTypeUpdate
      }
      const res = await getSpuRelSeriesInfoService(data)
      if (res?.retData) {
        this.$set(row, 'brandseriesOptions', res.retData)
      }
    },
    // 修改商品类型
    handleChangeByProductType (row) {
      this.updateProductNameFinal(row)
    },
    // 设置最终商品名称和助记码
    async updateProductNameFinal (row) {
      const data = {
        productName: row?.productNameUpdate,
        productType: row?.productTypeUpdate,
        productNameType: row?.productNameTypeUpdate,
        joinBrandName: row?.joinBrandName, // joinBrandName没有现值
      }
      const loadingFn = state => { this.tableInfo.loading = state }
      const res = await getProductNameFinalService(data, loadingFn)
      row.productNameFinalUpdate = res?.retData?.productNameFinal ?? ''
      row.helpCodeUpdate = res?.retData?.helpCode ?? ''
    }
  }
}
</script>
